<?php

namespace app\common\behavior;

use app\common\model\xilumarket\GroupChatRead;

class WebsocketMessage{
    public function createGroupMessage($new_msg) {
        $chatModel = new \app\common\model\xilumarket\GroupChat();
        $res = $chatModel->create($new_msg);
        $new_msg_id = $res->id;
        GroupChatRead::create([
            'user_id'   => $new_msg['send_user_id'],
            'session_id'    =>  $new_msg['session_id'],
            'group_chat_id' => $new_msg_id,
        ]);
        $data = $chatModel->field(['id', 'session_id', 'send_user_id', 'content', 'chat_type', 'createtime'])
            ->where('session_id',  $new_msg['session_id'])
            ->where('group_chat.id', $new_msg_id)
            ->with(['session', 'senduser' => function ($que) {
                $que->withField('id,nickname,avatar,gender');
            }])
            ->find();
        $returnData['is_group'] = true;
        $returnData['code'] = 1;
        $returnData['msg'] = '';
        $returnData['session_id'] =  $new_msg['session_id'];
        $returnData['data'] = $data->toArray();
        return $returnData;
    }

    public function createPersonalMessage($new_msg) {
        $chatModel = new \app\common\model\xilumarket\Chat;
        $res = $chatModel->save($new_msg);
        if (!$res) {
            $returnData['msg'] = '发送失败';
            return $returnData;
        }
        $new_msg_id = $chatModel->id;
        // 获取最新消息
        $data = $chatModel->field(['id', 'session_id', 'send_user_id', 'receive_user_id', 'content', 'chat_type', 'see_type', 'createtime',])->with(['senduser' => function ($que) {
            $que->withField('id,nickname,avatar,gender');
        }, 'receiveuser' => function ($que) {
            $que->withField('id,nickname,avatar,gender');
        }])->where('chat.id', $new_msg_id)->find();
        $returnData['code'] = 1;
        $returnData['msg'] = '';
        $returnData['data'] = $data->toArray();
        return $returnData;
    }
}